package org.icress.fusion.b2b

import org.icress.fusion.admin.RecordType
import org.hibernate.FetchMode as FM
import java.util.Date
import org.icress.fusion.wf.WorkflowHistory
import org.icress.fusion.ws.OutBound

import org.springframework.transaction.annotation.*

class SalesOrderAjaxService {

    static transactional = true

    //get dealer department
    def dealerDeaprtment(dealerSerialNumber){
        return Dealer.withCriteria(uniqueResult:true){
            createAlias 'department', 'dept'
            projections{
                property("dept.serialNumber")
                property("dept.name")
            }
            fetchMode "department", FM.JOIN
            eq("serialNumber", dealerSerialNumber)
        }        
    }

    //get industry list
    
    def industryList(term) {
        term = term.trim()
        return Industry.withCriteria{
            projections{
                property('id')
                property('shortName')
                property('serialNumber')
            }
            or{
                ilike("serialNumber", term + "%")
                ilike("shortName", "%"+term + "%")
                ilike("fullName", "%"+term + "%")
            }
            eq("isActive", true)
            maxResults(10)
            order("serialNumber", "asc")
        }
    }
    //get project list
    
    def projectList221(dealer, industry, term) {
        term = term.trim()
        dealer = (dealer != "")?dealer.toLong():-1L
        industry = (industry != "")?industry.toLong():-1L
        return ContractDetail.withCriteria{
            createAlias 'contract', 'm'
            createAlias 'contract.recordType', 'rt'
            projections{
                groupProperty('m.project')
                count('m.project')
            }
            fetchMode "contract", FM.JOIN
            fetchMode "contract.recordType", FM.JOIN
            eq("m.dealer.id", dealer)
			eq("m.industry.id", industry)
            eq("rt.serialNumber", "2")
            ge("expiryDate", new Date())
            or{
                ilike("m.project", "%"+term + "%")
                ilike("m.project", "%"+term + "%")
            }
            order("m.project", "asc")
            maxResults(10)
        }
    }
    
    def projectList224(dealer, industry, term) {
        term = term.trim()
        dealer = (dealer != "")?dealer.toLong():-1L
        industry = (industry != "")?industry.toLong():-1L
        return ContractDetail.withCriteria{
            createAlias 'contract', 'm'
            createAlias 'contract.recordType', 'rt'
            projections{
                groupProperty('m.project')
                count('m.project')
            }
            fetchMode "contract", FM.JOIN
            fetchMode "contract.recordType", FM.JOIN
            eq("m.dealer.id", dealer)
			eq("m.industry.id", industry)
            eq("rt.serialNumber", "1")
            ge("expiryDate", new Date())
            or{
                ilike("m.project", "%"+term + "%")
                ilike("m.project", "%"+term + "%")
            }
            order("m.project", "asc")
            maxResults(10)
        }
    }

    //get product list
    
    def productList(term) {
        return Product.withCriteria{
            projections {
                property('id')
                property('name')
                property('serialNumber')
                property('standard')
                property('price')
            }
            or{
                ilike("serialNumber", term + "%")
                ilike("standard", term + "%")
            }
            and{
                not{like("serialNumber", '1%')}
                not{like("serialNumber", '2%')}
                not{like("serialNumber", '4%')}
            }
            eq("isActive", true)
            maxResults(10)
            order("serialNumber", "asc")
        }

    }
    //get product category, recordtype serial number is 2
    def productCategory(serialNumber) {
        return ProductCategory.withCriteria(uniqueResult:true){
            createAlias 'product', 'p'
            createAlias 'category', 'c'
            createAlias 'category.recordType', 'rt'
            projections {
                property('c.name')
                property('c.id')
            }
            join "product"
            join "category"
            join "category.recordType"
            eq("p.serialNumber", serialNumber)
            eq("rt.serialNumber", "2")
            eq("p.isActive", true)
        }
    }
    
    def isAllowZeroPrice(serialNumber) {
        def result = 'N'
        def isAllowZeroPrice = ProductCategory.withCriteria{
            createAlias 'product', 'p'
            createAlias 'category', 'c'
            createAlias 'category.recordType', 'rt'
            projections {
                property('c.isAllowZeroPrice')
            }
            join "product"
            join "category"
            join "category.recordType"
            eq("p.serialNumber", serialNumber)
            eq("rt.serialNumber", "5")
            eq("p.isActive", true)
        }
        log.info "isAllowZeroPrice=${isAllowZeroPrice}, size=${isAllowZeroPrice.size()}"
        if(isAllowZeroPrice.size() > 0){//有第五个属性，true为允许，false和null为不允许
            result = (isAllowZeroPrice[0] == true)?'Y':'N'
        }else{//没有第五个属性，默认为允许
            result = 'Y'
        }
        return result
    }

    def isAllowSpecialDiscount(serialNumber) {
        def result = ProductCategory.withCriteria(uniqueResult:true){
            createAlias 'product', 'p'
            createAlias 'category', 'c'
            createAlias 'category.recordType', 'rt'
            projections {
                property('c.isAllowSpecialDiscount')
            }
            join "product"
            join "category"
            join "category.recordType"
            eq("p.serialNumber", serialNumber)
            eq("rt.serialNumber", "5")
            eq("p.isActive", true)
        }
        return (result == true)?"Y":"N"
    }


    //get product discount, recordtype serial number is 5
    def productDiscount(serialNumber) {
        def discount = ProductCategory.withCriteria(uniqueResult:true){
            createAlias 'product', 'p'
            createAlias 'category', 'c'
            createAlias 'category.recordType', 'rt'
            projections {
                property('c.discount')
            }
            join "product"
            join "category"
            join "category.recordType"
            eq("p.serialNumber", serialNumber)
            eq("rt.serialNumber", "5")
            eq("p.isActive", true)
        }
        return discount?:1
    }

    //get product delivery cycle, recordtype serial number is 2
    def productDeliveryCycle(serialNumber) {
        return ProductCategory.withCriteria(uniqueResult:true){
            createAlias 'product', 'p'
            createAlias 'category', 'c'
            createAlias 'category.recordType', 'rt'
            projections {
                property('c.deliveryCycle')
            }
            join "product"
            join "category"
            join "category.recordType"
            eq("p.serialNumber", serialNumber)
            eq("rt.serialNumber", "2")
            eq("p.isActive", true)
        }
    }
   
    //get product special discount-sales order record type = 221
    def productContractDetail221(dealerId, proejct, categoryId){
        dealerId = dealerId ?: ""
        dealerId = (dealerId != "") ? dealerId.toLong():-1L
        proejct = proejct ?:""
        categoryId = categoryId ?: -1L

        def result = ContractDetail.withCriteria(uniqueResult:true){
            createAlias 'contract', 'm'
            createAlias 'contract.recordType', 'rt'
            projections{
                property('id')
                property('discount')
                property('specialDiscount')
                property('finalDiscount')
                property('m.serialNumber')
                property('serialNumber')
            }
            fetchMode "contract", FM.JOIN
            fetchMode "contract.recordType", FM.JOIN
            eq("rt.serialNumber", "2")
            eq("m.dealer.id", dealerId)
            eq("category.id", categoryId)
            ge("expiryDate", new Date())
            eq("m.project", proejct)
            order("specialDiscount", "desc")
            maxResults(1)
        }
        return result
    }
    //get product special discount-sales order record type = 221
    
    def productContractDetail224(dealerId, proejct, categoryId){
        dealerId = dealerId ?: ""
        dealerId = (dealerId != "") ? dealerId.toLong():-1L
        proejct = proejct ?:""
        categoryId = categoryId ?: -1L

        def result = ContractDetail.withCriteria(uniqueResult:true){
            createAlias 'contract', 'm'
            createAlias 'contract.recordType', 'rt'
            projections{
                property('id')
                property('discount')
                property('specialDiscount')
                property('finalDiscount')
                property('m.serialNumber')
                property('serialNumber')
            }
            fetchMode "contract", FM.JOIN
            fetchMode "contract.recordType", FM.JOIN
            eq("rt.serialNumber", "1")
            eq("m.dealer.id", dealerId)
            eq("category.id", categoryId)
            ge("expiryDate", new Date())
            eq("m.project", proejct)
            order("specialDiscount", "desc")
            maxResults(1)
        }
        return result
    }

    
	def workflowHistory(salesOrderId){
		salesOrderId = (salesOrderId != "") ? salesOrderId:-1L
		return WorkflowHistory.withCriteria(){
			eq("objectName", 'salesOrder')
			eq("objectId", salesOrderId)
			order("id", "desc")
		}
	}

    
    def outBoundMessage(salesOrderId){
		salesOrderId = (salesOrderId != "") ? salesOrderId:-1L
		return OutBound.withCriteria(){
			eq("objectName", 'salesOrder')
			eq("objectId", salesOrderId)
			order("id", "desc")
		}
	}

    //获取OA特价申请单单头ID
    def getContractId(contractDetailId){
        return ContractDetail.withCriteria(uniqueResult:true){
            createAlias 'contract', 'head'          
            projections {
                property('head.id') 
            }
            join "contract"
            eq("id", contractDetailId.toLong())
        }
    }

    //获取OA特价申请单编号
    def getContractDetailSerialNumber(contractDetailId){
        return ContractDetail.withCriteria(uniqueResult:true){
            createAlias 'contract', 'head'          
            projections {
                property('head.serialNumber')
                property('serialNumber')
            }
            join "contract"
            eq("id", contractDetailId.toLong())
        }    
    }
}
